/*
 * 创建日期 2010-7-14
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.compile;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.List;

import  org.fantasy.common.util.StringUtil;

/**
 * Service翻译器
 * @author: 王文成
 * @version: 1.0
 * @since 2010-7-14
 */
public class SqlConvertor {

    private String sql;

    public SqlConvertor(String sql) {
        this.sql = sql;
    }
    
    /**
     * 转化为JAVA代码
     * @return
     * @throws Exception
     */
    public String toJava() throws Exception {
        BufferedReader bf = new BufferedReader(new StringReader(sql.toString()));
        String line = null;
        StringBuilder code = new StringBuilder(128);
        code.append("StringBuilder sql = new StringBuilder(512);\n");
        while ((line = bf.readLine()) != null) {
            code.append(transform(line));
            code.append("\n");
        }
        return covert(code.toString());
    }
    
    /**
     * 参数转换
     * #custId# 转换为 " + rm.getString("custId") + "
     * @param code
     * @return
     */
    private String covert(String code ){
    	List<String> params = StringUtil.matchs(code, "#(\\w+)#", 1);
        for (String param : params) {
            String key = param.trim();
            	code = code.replace("#" + param + "#", "\" + rm.getString(\"" + key + "\") + \"");
        }
        return code;
    }
    
    /**
     * 解释每一行
     * @param line
     * @return
     */
    private String transform(String line) {
        String regexp = ".*\\((.+)\\).*";
        if (line.matches(".*\\bif\\b.*")) {
            if (line.contains("==")) {
                String exp = line.replaceAll(regexp, "$1");
                String[] values = exp.split("==");
                String left = values[0].trim();
                String right = values[1].trim();
                return line.replace(exp, getIfCode(left, right, true));
            } else if (line.contains("!=")) {
                String exp = line.replaceAll(regexp, "$1");
                String[] values = exp.split("!=");
                String left = values[0].trim();
                String right = values[1].trim();
                return line.replace(exp, getIfCode(left, right, false));
            } else {
                String exp = line.replaceAll(regexp, "$1");
                String param = exp.trim();
                return line.replace(exp, getValidCode(param));
            }
        } else if (line.trim().startsWith("}") || line.trim().endsWith("{")) {
            return line;
        } else {
            StringBuffer sql = new StringBuffer();
            sql.append("sql.append(\"");
            sql.append(line + "\\n");
            sql.append("\");");
            return sql.toString();
        }
    }
    
    /**
     * 转化为if代码
     * @param left
     * @param right
     * @param equals
     * @return
     */
    private String getIfCode(String left, String right, boolean equals) {
        StringBuffer code = new StringBuffer();
        if (!equals) {
            code.append("!");
        }
        if (left.contains("\"")) {
            code.append(left + ".equals(");
        } else {
            code.append("rm.getString(\"" + left + "\").equals(");
        }
        if (right.contains("\"")) {
            code.append(right);
        } else {
            code.append("rm.getString(\"" + right + "\")");
        }
        code.append(")");
        return code.toString();
    }
    
    /**
     * 转化为valid代码
     * @param param
     * @return
     */
    private String getValidCode(String param) {
        StringBuffer code = new StringBuffer();
        code.append("rm.isValid(\"" + param + "\")");
        return code.toString();
    }
    
    public static void main(String[] args) throws Exception {
    	StringBuilder sql = new StringBuilder(512);
    	sql.append("select * from user_info a  \n");
    	sql.append("if( userName ){ \n");
    	sql.append("  a.WISField001 = :userName \n");
    	sql.append("} \n");
    	sql.append("if( address ){ \n");
    	sql.append("  a.WISField003 = #custId# \n");
    	sql.append("} \n");
    	SqlConvertor convertor = new SqlConvertor(sql.toString());
    	System.out.println( convertor.toJava() );
	}
}
